﻿using System;
using System.Collections.Generic;
using System.Xml;
using IURIP;
using URIP.Factory;
using URIP.Tool;

namespace URIP.Core
{
    public class ProcessTemplate : BaseTemplate, IProcessTemplate
    {
        public ProcessTemplate(ITarget target, ITemplate parentTemplate)
            : base(target, parentTemplate)
        {
        }

        protected string m_keyTemplate = "";
        protected Dictionary<string, IActionTemplate> m_actionTemplates = new Dictionary<string, IActionTemplate>();

        public string KeyTemplate
        {
            get { return m_keyTemplate; }
        }
        public Dictionary<string, IActionTemplate> ActionTemplates
        {
            get
            {
                return null;
            }
        }

        public override IRunable CreateRunable(IRunable parentRunable)
        {
            var res = new Process(this, parentRunable);
            return res;
        }
        public override void InitByConfiguration(XmlNode node)
        {
            m_keyTemplate = Util.GetAttributeValue(node, "key");
            if (string.IsNullOrEmpty(m_keyTemplate))
            {
                throw new Exception(string.Format("The process definition for target {0} has no valid key attribute!", Target.Name));
            }
            if(node.HasChildNodes)
            {
                var tmpNode = node.FirstChild;
                while (tmpNode != null)
                {
                    if (tmpNode.Name == "Action")
                    {
                        var template = new ActionTemplate(Target, this);
                        template.InitByConfiguration(tmpNode);
                        ChildrenTemplates.AddLast(template);
                        Task.Logger.LogInfo("Finish loading ActionTemplate {0}.", template.Name);
                    }
                    else if (tmpNode.Name == "Rule")
                    {
                        var template = RuleTemplateFactory.GetRuleTemplate(tmpNode, Target, this);
                        ChildrenTemplates.AddLast(template);
                        Task.Logger.LogInfo("Finish loading Rule {0}.", template.Name);
                    }
                    tmpNode = tmpNode.NextSibling;
                }
                List<string> actionDataBlocks = new List<string>();
                foreach (var kvp in ActionTemplates)
                {
                    actionDataBlocks.Add(kvp.Value.ReferenceDataBlock);
                }
                foreach (var kvp in Target.DataBlocks)
                {
                    if (!actionDataBlocks.Contains(kvp.Key))
                    {
                        Task.Logger.LogWarning("The data block {0} is not used in action for target {1}", kvp.Key, Target.Name);
                    }
                }
            }
        }
    }
}
